﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.ESGRatings.Service.Models;
using Sustainalytics.ESGRatings.Service.Models.Common;
using Sustainalytics.ESGRatings.Service.Models.DTOs.RpIndicators;
using Sustainalytics.Utils;
using Sustainalytics.Auth.Claims;
using Sustainalytics.ESG.Entities;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using Sustainalytics.DataLayer.EsgRatings;
using System.Web.Http.Cors;

namespace Sustainalytics.ESGRatings.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ClaimsChecker("api/v1/company/esg")]
    [RoutePrefix("api/v1/company")]
    //[AutoInvalidateCacheOutput]
    [LogControllerFilter(true, true, false)]
    public class EsgRpIndicatorController : ApiController
    {

        public EsgRpIndicatorController()
        {
            Setup();
        }

        public EsgRpIndicatorController(IOnlineResearchProductsBusinessLogicUnit service)
        {
            _service = service;
        }

       // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("{companyId}/esgRpIndicator")]
        [UniverseChecker("universeIds", AccountFeature.EsgRatingsOnlineReport)]
        public HttpResponseMessage Get([FromUri]Guid companyId,[FromUri] Guid esgProfileId, [FromUri]string clusterName = null, [FromUri]EsgThemeEnum? theme = null, [FromUri]int skip = 0, [FromUri]int take = 0, [FromUri]int[] universeIds = null, [FromUri]string indicatorNumber = null)
        {
            try
            {
                if (esgProfileId == Guid.Empty) return Request.CreateResponse(HttpStatusCode.BadRequest,
                                        new { ErrorStatusCode = WebAPIGeneralErrorCodes.InvalidEsgProfileId });
                var data = _service.GetIndicatorsByCompanyThemeAndCluster(companyId,esgProfileId, theme.HasValue ? theme.Value.ToString() : string.Empty, clusterName, universeIds, indicatorNumber, skip, take).ToList();

                IEnumerable<EsgRpIndicatorDto> result = data.Select(x => x.ToDto());
                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (ESGReasearchNotFoundException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message
                });

            }
            catch (ESGReasearchNotInUniversesException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message
                });

            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return this.Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
                
            }
        }

      
      
        private IOnlineResearchProductsBusinessLogicUnit _service;


        private void Setup()
        {

            IStandardIndicatorsRepository standardIndicatorsRepository =
                new StandardIndicatorsRepository(ClientDWConnection.GetConnectionString());

            IRepositoryCollection<IndicatorTemplate> templateIndicatorsRepository =
                new RepositoryCollection<IndicatorTemplate>(ClientDWConnection.GetConnectionString());

            IControversyIndicatorsRepository controversyIndicatorRepository = 
                new ControversyIndicatorsRepository(ClientDWConnection.GetConnectionString());
            IRepositoryCollection<RPCompanyESGComputationResult> computationRepository = new RepositoryCollection<RPCompanyESGComputationResult>(ClientDWConnection.GetConnectionString());

            _service = _service ?? new OnlineResearchProductsBusinessLogicUnit(templateIndicatorsRepository, standardIndicatorsRepository, controversyIndicatorRepository, computationRepository);
        }
  
    }
}
